package com.sxkiler.demo.rpc.server;

import com.sxkiler.demo.rpc.common.MessageDecoder;
import com.sxkiler.demo.rpc.common.MessageEncoder;
import com.sxkiler.demo.rpc.utils.InitAnnotatedObject;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;

public class NettyServer {

    public static void main(String[] args) throws InterruptedException {
        //NacosTemplate nacosTemplate = new NacosTemplate(); //集成nacos才用到，可以去掉
        NettyServerHandler nettyServerHandler = new NettyServerHandler();
        EventLoopGroup parentGroup = new NioEventLoopGroup();
        EventLoopGroup childGroup = new NioEventLoopGroup();
        try {

            ServerBootstrap bootstrap = new ServerBootstrap();
            bootstrap.group(parentGroup, childGroup)
                    .channel(NioServerSocketChannel.class)
                    .childHandler(new ChannelInitializer<SocketChannel>() {

                        @Override
                        protected void initChannel(SocketChannel ch) throws Exception {

                            ChannelPipeline pipeline = ch.pipeline();
                            pipeline.addLast(new MessageDecoder());//自定义的解码器
                            pipeline.addLast(new MessageEncoder());//自定义的编码器
                            pipeline.addLast(nettyServerHandler);
                        }
                    });

            ChannelFuture future = bootstrap.bind(8881).sync();
            if (future.isSuccess()){
                nettyServerHandler.setBeans(InitAnnotatedObject.init());//将带有@RpcService注解的类加载到“Bean容器”中
                System.out.println("成功加载bean,数量："+nettyServerHandler.getBeans().size());
                System.out.println("已加载的beans：--["+nettyServerHandler.getBeans().toString()+"]--");
                System.out.println("服务器已启动。。。");
            }
            future.channel().closeFuture().sync();

        }catch (Exception e){
            e.printStackTrace();
        } finally {
            parentGroup.shutdownGracefully();
            childGroup.shutdownGracefully();
        }
    }
}


